import { getTalentchainHome } from '@/api/talent'
import Cookies from 'js-cookie'

export const getWorkCategoryTree = () => {
  // 尝试从本地存储获取数据
  const workCategoryTree = sessionStorage.getItem('workCategoryTree')
  if (workCategoryTree) {
    return Promise.resolve(JSON.parse(workCategoryTree))
  }

  // 如果没有找到或数据无效，则从远程获取
  return getTalentchainHome()
    .then((res) => {
      if (res.code === 20000) {
        // 将远程数据保存到本地存储
        sessionStorage.setItem('workCategoryTree', JSON.stringify(res.data))
        // 返回找到的数据项
        return res.data
      } else {
        throw new Error(`Failed to fetch data: ${res.message || 'Unknown error'}`)
      }
    })
    .catch((error) => {
      console.error('Error fetching data:', error)
      throw error // 重新抛出错误，以便调用者可以处理它
    })
}

// 判断是否为有效的电子邮件格式
export function isValidEmail(email) {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  return emailRegex.test(email)
}

// 判断手机号码是否合法
export function isValidPhone(phone) {
  const phoneRegex = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
  return phoneRegex.test(phone)
}

export function setCookie(name, value, domain, secure) {
  const day = 30 // cookie过期天数为30天
  let str = ''
  if (window.location.host === 'localhost:8880') str = domain
  else if (window.location.host === 'www.rcepdev.com:8880')
    str = '.rcepdev.com' // 兼容测试环境
  else {
    const host = window.location.host
    const arr = host.split('.')
    str = '.' + arr[arr.length - 2] + '.' + arr[arr.length - 1]
  }
  const myName = name
  const myValue = value
  Cookies.set(myName, myValue, {
    expires: day,
    path: '/',
    domain: str,
    // HttpOnly: true,
    secure: secure ? secure : false,
    // sameSite: 'strict'
  })
}

export function isLogin(callback, loginCallback) {
  if (Cookies.get('token')) {
    callback && callback()
  } else {
    showConfirmDialog({
      title: '您未登录',
      message: '前往登录？',
    })
      .then(() => {
        // on close
        loginCallback && loginCallback()
      })
      .catch(() => {})
  }
}
